package com.yungu.swift.assets.driver.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.yungu.swift.assets.driver.dao.CarMapper;
import com.yungu.swift.assets.driver.dao.DriverChangeCarMapper;
import com.yungu.swift.assets.driver.dao.DriverMapper;
import com.yungu.swift.assets.driver.model.dto.*;
import com.yungu.swift.assets.driver.model.param.AdminDriverChangeCarParam;
import com.yungu.swift.assets.driver.service.CarInsuranceService;
import com.yungu.swift.assets.driver.service.CarService;
import com.yungu.swift.assets.driver.service.DriverChangeCarService;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.common.service.CommonSmsService;
import com.yungu.swift.constants.DriverConstant;
import com.yungu.swift.system.marketing.service.MarketingChannelLogService;
import com.yungu.swift.system.marketing.service.MarketingChannelService;
import com.yungu.swift.system.marketing.service.MarketingGiftService;
import com.yungu.swift.system.marketing.service.MarketingInviteLogService;
import com.yungu.swift.system.sys.model.dto.SysBusinessOperateLogDto;
import com.yungu.swift.system.sys.model.enums.SysBusinessOperateEnum;
import com.yungu.swift.system.sys.service.SysAccountDriverService;
import com.yungu.swift.system.sys.service.SysBusinessOperateLogService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 司机申请业务逻辑接口实现类
 *
 * @author cuixiuyin - Generate
 * @version 1.1.1-SNAPSHOT
 * @since 2018-07-05 17:57
 */
@Slf4j
@Service
public class DriverChangeCarServiceImpl extends BaseServiceImpl<DriverChangeCarDto> implements DriverChangeCarService {
    @Autowired
    private DriverChangeCarMapper driverChangeCarMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private CarService carService;
    @Autowired
    private CarInsuranceService carInsuranceService;
    @Autowired
    private DriverService driverService;

    @Reference
    private CommonSmsService commonSmsService;
    @Reference
    private MarketingInviteLogService marketingInviteLogService;
    @Reference
    private MarketingGiftService marketingGiftService;
    @Reference
    private MarketingChannelService marketingChannelService;
    @Reference
    private MarketingChannelLogService marketingChannelLogService;
    @Reference
    private SysAccountDriverService sysAccountDriverService;
    @Reference
    private SysBusinessOperateLogService sysBusinessOperateLogService;

    @Override
    protected IMapper<DriverChangeCarDto> getMapper() {
        return driverChangeCarMapper;
    }

    @Override
    @Transactional
    public ResponseData<Boolean> pass(AdminDriverChangeCarParam changeCarParam) {
        try {
            List<DriverChangeCarDto> list = driverChangeCarMapper.list(MapUtils.build("uuid", changeCarParam.getUuid()));
            if (CollectionUtils.isNotEmpty(list)) {
                DriverChangeCarDto changeDto = list.get(0);
                Map<String, Object> params = MapUtils.build(4);
                //检验手机号
                params.put("uuid", changeDto.getDriverUuid());
                ResponseData<DriverDto> driverDtoResponseData = driverService.get(changeDto.getDriverUuid());
                if (driverDtoResponseData.isSuccess() && driverDtoResponseData.getData() == null) {
                    return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "未获取到当前司机信息");
                }
                DriverDto driverDto = driverDtoResponseData.getData();
                //查询当前库中是否有该车辆，不存在则将车辆保存
                if (StringUtils.isNotEmpty(changeDto.getPlateNum())) {
                    ResponseData<CarDto> responseData = carService.get(MapUtils.build("plateNum", changeDto.getPlateNum()));
                    if (responseData.isSuccess() && responseData.getData() == null) {
                        //将该车辆保存到数据库中
                        CarDto carDto = new CarDto();
                        carDto.setUuid(StringUtils.buildUUID());
                        carDto.setPlateNum(changeDto.getPlateNum());
                        carDto.setAppid(changeDto.getAppid());
                        carDto.setAgentUuid(changeDto.getAgentUuid());
                        carDto.setCompanyUuid(changeDto.getCompanyUuid());
                        carDto.setCarModelUuid(changeDto.getCarModelUuid());
                        carDto.setCarColor(changeDto.getCarColor());
                        carDto.setModel(changeDto.getModel());
                        carDto.setBrand(changeDto.getBrand());
                        carDto.setState(1);
                        carDto.setPlateColor(String.valueOf(changeDto.getEnergyType()));
                        carDto.setDrivingLicenseImg(changeDto.getDrivingLicenceHomeImg());
                        carDto.setDrivingLicenseSubImg(changeDto.getDrivingLicenceSubImg());
                        carDto.setManCarImg(changeDto.getMancarImg());
                        carDto.setCarAngle45Img(changeDto.getCarAngle45Img());
                        carDto.setCreateOn(new Date());
                        carService.add(carDto);
                        //添加车辆保险数据
                        CarInsuranceDto carInsuranceDto = new CarInsuranceDto();
                        carInsuranceDto.setUuid(StringUtils.buildUUID());
                        carInsuranceDto.setCarUuid(carDto.getUuid());
                        carInsuranceDto.setAgentUuid(changeDto.getAgentUuid());
                        carInsuranceDto.setCompanyUuid(changeDto.getCompanyUuid());
                        carInsuranceDto.setCreateOn(new Date());
                        carInsuranceService.add(carInsuranceDto);
                        driverDto.setCarUuid(carDto.getUuid());
                    } else if (responseData.isSuccess() && responseData.getData() != null) {
                        //存在，则查询当前车辆是否绑定其他司机
                        ResponseData<List<DriverDto>> driver = driverService.list(MapUtils.build("carUuid", responseData.getData().getUuid()));
                        if(!driver.getData().isEmpty() && !driver.getData().get(0).getUuid().equals(changeDto.getDriverUuid())) {
                            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "该车辆已经绑定其他司机");
                        }
                        //修改车辆信息
                        CarDto car = responseData.getData();
                        CarDto carDto = new CarDto();
                        carDto.setUuid(car.getUuid());
                        carDto.setAgentUuid(changeDto.getAgentUuid());
                        carDto.setCompanyUuid(changeDto.getCompanyUuid());
                        carDto.setCarModelUuid(changeDto.getCarModelUuid());
                        carDto.setCarColor(changeDto.getCarColor());
                        carDto.setModel(changeDto.getModel());
                        carDto.setBrand(changeDto.getBrand());
                        carDto.setPlateColor(String.valueOf(changeDto.getEnergyType()));
                        carDto.setDrivingLicenseImg(changeDto.getDrivingLicenceHomeImg());
                        carDto.setDrivingLicenseSubImg(changeDto.getDrivingLicenceSubImg());
                        carDto.setManCarImg(changeDto.getMancarImg());
                        carDto.setCarAngle45Img(changeDto.getCarAngle45Img());
                        carDto.setUpdateOn(new Date());
                        carService.update(carDto);
                    }
                }
                driverDto.setCompanyUuid(changeDto.getCompanyUuid());
                driverDto.setAgentUuid(changeDto.getAgentUuid());
                driverDto.setUpdateBy(changeCarParam.getUserUuid());
                driverDto.setUpdateOn(new Date());
                driverDto.setGetDriverLicenseDate(changeDto.getCarRegisteredTime());
                driverMapper.edit(driverDto);

                //更新审核表
                DriverChangeCarDto changeCarDto = new DriverChangeCarDto();
                changeCarDto.setUuid(changeDto.getUuid());
                changeCarDto.setRemark(null);
                changeCarDto.setStatus(DriverConstant.DRIVER_CHECK_PASS);
                changeCarDto.setUpdateStatus(1);
                changeCarDto.setUpdateBy(changeCarParam.getUserUuid());
                changeCarDto.setUpdateOn(new Date());
                driverChangeCarMapper.edit(changeCarDto);
                //插入操作日志
                addOperetaLog(changeCarParam, changeCarDto, "", driverDto.getMobile(), driverDto.getName());
                return ResponseData.buildSuccessResponse("审核成功", Boolean.TRUE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "系统异常，审核失败");
    }


    @Override
    public ResponseData<Boolean> reject(AdminDriverChangeCarParam changeCarParam) {
        List<DriverChangeCarDto> list = driverChangeCarMapper.list(MapUtils.build("uuid", changeCarParam.getUuid()));
        if (CollectionUtils.isNotEmpty(list)) {
            DriverChangeCarDto driverChangeCarDto = list.get(0);
            DriverChangeCarDto driverChangeParam = new DriverChangeCarDto();
            driverChangeParam.setUuid(driverChangeCarDto.getUuid());
            driverChangeParam.setStatus(DriverConstant.DRIVER_CHECK_NOT_PASS);
            driverChangeParam.setRemark(changeCarParam.getRemark());
            driverChangeParam.setUpdateBy(changeCarParam.getUserUuid());
            driverChangeParam.setUpdateOn(new Date());
            if (driverChangeCarMapper.edit(driverChangeParam) > 0) {
                //插入操作日志
                addOperetaLog(changeCarParam, driverChangeParam, changeCarParam.getRemark(), "", "");
                return ResponseData.buildSuccessResponse("驳回成功", Boolean.TRUE);
            }
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "驳回异常");
    }

    @Override
    public ResponseData<DriverCheckDto> getLatest(Map<String, Object> map) {
        return ResponseData.buildSuccessResponse(driverChangeCarMapper.getLatest(map));
    }

    @Override
    public ResponseData<Integer> insert(DriverChangeCarDto dto) {
        //查询当前车辆是否存在
        if (StringUtils.isNotEmpty(dto.getPlateNum())) {
            ResponseData<CarDto> responseData = carService.get(MapUtils.build("plateNum", dto.getPlateNum()));
            if (responseData.isSuccess() && responseData.getData() != null) {
                //存在，则查询当前车辆是否绑定其他司机
                ResponseData<List<DriverDto>> driver = driverService.list(MapUtils.build("carUuid", responseData.getData().getUuid()));
                if(!driver.getData().isEmpty() && !driver.getData().get(0).getUuid().equals(dto.getDriverUuid())) {
                    return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "该车辆已经绑定其他司机");
                }
            }
        }
        //判断是否选择代理和公司
        if(dto.getAgentUuid() == null || dto.getAgentUuid().equals("")) {
            dto.setAgentUuid("5f071b90b0514a099c11a2bfc535e917");
        }
        if(dto.getCompanyUuid() == null || dto.getCompanyUuid().equals("")) {
            dto.setCompanyUuid("21ee7e1ae8eb449a83405e49cb3582a1");
        }
        dto.setStatus(1);
        dto.setCreateOn(new Date());
        dto.setIsNotice(0);
        dto.setUpdateStatus(0);
        dto.setCreateBy(dto.getDriverUuid());
        return ResponseData.buildSuccessResponse(driverChangeCarMapper.add(dto));
    }

    private void addOperetaLog(AdminDriverChangeCarParam changeCarParam, DriverChangeCarDto driverChangeCarDto, String remark, String driverMobile, String driverName) {
        try {
            SysBusinessOperateLogDto operateLogDto = new SysBusinessOperateLogDto();
            operateLogDto.setBeforeValue("未审核");
            String driverInfo = "(" + driverName + "-" + driverMobile + ")";
            if (driverChangeCarDto.getStatus().equals(DriverConstant.DRIVER_CHECK_PASS)) {
                operateLogDto.setAfterValue("审核通过" + driverInfo);
                operateLogDto.setOperationCode(SysBusinessOperateEnum.DRIVER_AUDIT_PASS.getCode());
                operateLogDto.setOperationName(SysBusinessOperateEnum.DRIVER_AUDIT_PASS.getName());
            } else {
                operateLogDto.setAfterValue("审核拒绝" + driverInfo);
                operateLogDto.setOperationCode(SysBusinessOperateEnum.DRIVER_AUDIT_REJECT.getCode());
                operateLogDto.setOperationName(SysBusinessOperateEnum.DRIVER_AUDIT_REJECT.getName());
            }

            operateLogDto.setOperationDescribe("客服审核司机更换车辆申请");
            operateLogDto.setCreateBy(changeCarParam.getUserUuid());
            operateLogDto.setCreateOn(new Date());
            operateLogDto.setAgentUuid(changeCarParam.getUserAgentUuid());
            operateLogDto.setCompanyUuid(changeCarParam.getUserCompanyUuid());
            operateLogDto.setAppid(changeCarParam.getAppid());
            operateLogDto.setUuid(StringUtils.buildUUID());
            operateLogDto.setOperationUserIp(changeCarParam.getUserip());
            operateLogDto.setRemark(remark);
            sysBusinessOperateLogService.add(operateLogDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
